// src/pages/Medical/Consultation/Detail.jsx
import React,{useState,useEffect} from 'react';
import { NavBar, Card, Button, Space,Toast} from 'antd-mobile';
import { useNavigate,useLocation} from 'react-router-dom';
import StatusTag from '../StatusTag';
import axios from 'axios';

// Static data from index.jsx
const staticConsultations = [
  {
    _id: '1',
    patientName: '张三',
    age: 45,
    department: '心内科',
    status: 'pending',
    expectedTime: '2024-01-20',
    desc: '心绞痛，需要进一步诊断',
    datetime:'2024-01-21'
  },
  {
    _id: '2',
    patientName: "李四",
    age: 38,
    department: "神经内科",
    status: "approved",
    expectedTime: "2024-02-15",
    desc: "头痛伴有眩晕，初步诊断为偏头痛",
    datetime:'2025-01-21'
  },
  {
    _id: '3',
    patientName: "王五",
    age: 52,
    department: "骨科",
    status: "rejected",
    expectedTime:"2024-03-05",
    desc: "腰椎间盘突出，建议物理治疗",
    datetime:'2024-03-6'
  },
  {
    _id: '4',
    patientName: "赵六",
    age: 29,
    department: "消化内科",
    status: "pending",
    expectedTime: "2024-04-10",
    desc: "慢性胃炎，需胃镜检查确认",
    datetime:'2024-11-21'
  }
];

const ConsultationDetail = () => {
  const navigate = useNavigate();
  const [huans, setHuan] = useState({});
  const location = useLocation();
  const [_id, setId] = useState('');

  const gethuanlist = () => {
    if (!_id) return; // Don't make the API call if ID is not set
    
    // First check if the ID exists in static data
    const staticItem = staticConsultations.find(item => item._id === _id);
    if (staticItem) {
      console.log('Using static data for ID:', _id);
      setHuan(staticItem);
      return;
    }
    
    // If not in static data, fetch from API
    console.log('Fetching from API for ID:', _id);
    const timestamp = new Date().getTime();
    axios.get(`http://localhost:3000/huan/edit?_id=${_id}&_t=${timestamp}`)
      .then((res) => {
        console.log('API Response:', res.data);
        
        if (res.data && res.data.list) {
          // If list is an array, take the first item
          if (Array.isArray(res.data.list) && res.data.list.length > 0) {
            setHuan(res.data.list[0]);
          } 
          // If list is an object, use it directly
          else if (typeof res.data.list === 'object') {
            setHuan(res.data.list);
          }
          // If we have data directly in res.data
          else if (typeof res.data === 'object' && Object.keys(res.data).length > 0) {
            setHuan(res.data);
          }
          else {
            console.error('Unexpected data format:', res.data);
            Toast.show({
              content: '数据格式不正确',
              position: 'center',
            });
          }
        } else {
          console.error('Empty or invalid response:', res.data);
          Toast.show({
            content: '获取数据失败',
            position: 'center',
          });
        }
      })
      .catch(error => {
        console.error('Error fetching consultation details:', error);
        Toast.show({
          content: '获取数据失败',
          position: 'center',
        });
      });
  };

  const handleAccept = async () => {
    try {
      Toast.show({
        content: '已接受会诊',
        position: 'center',
      });
      navigate(-1);
    } catch (error) {
      console.error('Error accepting consultation:', error);
      alert('操作失败');
    }
  };

  // Handle reject consultation
  const handleReject = async () => {
    try {
      Toast.show({
        content: '已拒绝会诊',
        position: 'center',
      });
      navigate(-1);
    } catch (error) {
      console.error('Error rejecting consultation:', error);
      alert('操作失败');
    }
  };

  useEffect(() => {
    // Extract ID from URL query parameters
    const queryParams = new URLSearchParams(location.search);
    const id = queryParams.get('_id');
    
    if (id) {
      setId(id);
      console.log('Setting ID:', id);
    } else {
      Toast.show({
        content: '未找到会诊ID',
        position: 'center',
      });
      navigate(-1);
    }
  }, [location.search, navigate]);

  // Separate useEffect for fetching data when ID changes
  useEffect(() => {
    if (_id) {
      console.log('Fetching data for ID:', _id);
      gethuanlist();
    }
  }, [_id]);

  // Fallback data in case API fails
  const fallbackData = {
    patientName: '未知',
    age: '未知',
    department: '未知',
    status: 'unknown',
    desc: '无法获取病情描述',
    expectedTime: '未知',
    datetime: '未知'
  };

  // Use fallback data if huans is empty
  const displayData = Object.keys(huans).length > 0 ? huans : fallbackData;

  return (
    <div className="consultation-detail">
      <NavBar onBack={() => navigate(-1)}>会诊详情</NavBar>

      <Card title="基本信息">
        <div className="info-item">
          <span className="label">患者姓名：</span>
          <span>{displayData.patientName}</span>
        </div>
        <div className="info-item">
          <span className="label">年龄：</span>
          <span>{displayData.age}岁</span>
        </div>
        <div className="info-item">
          <span className="label">科室：</span>
          <span>{displayData.department}</span>
        </div>
        <div className="info-item">
          <span className="label">状态：</span>
          <StatusTag status={displayData.status} />
        </div>
      </Card>

      <Card title="病情描述" style={{ marginTop: '12px' }}>
        <p>{displayData.desc}</p>
      </Card>

      <Card title="会诊信息" style={{ marginTop: '12px' }}>
        <div className="info-item">
          <span className="label">申请时间：</span>
          {/* 格式化时间 */}
          <span>{displayData.expectedTime ? new Date(displayData.expectedTime).toLocaleString() : '未知'}</span>
        
        </div>
        <div className="info-item">
          <span className="label">期望会诊时间：</span>
          <span>{displayData.datetime ? new Date(displayData.datetime).toLocaleString() : '未知'}</span>

    
        </div>
      </Card>

      <div style={{ padding: '16px' }}>
        <Space direction="vertical" block>
          <Button
            block
            color="primary"
            onClick={() => {handleAccept()}}
          >
            接受会诊
          </Button>
          <Button
            block
            onClick={() => {handleReject()}}
          >
            拒绝会诊
          </Button>
        </Space>
      </div>
    </div>
  );
};

export default ConsultationDetail;